/**
 * Created by Administrator on 2015/5/5.
 */
var autoinc = require('mongoose-auto-increment');
var model = {UserModel: null, TagModel: null, CatalogModel: null, ArticleModel: null, WidgetModel: null};

function setAutoId(schema, modelName){
    schema.plugin(autoinc.plugin, { model: modelName, field: 'id', startAt: 1});
}
/*
 Schema ： 一种以文件形式存储的数据库模型骨架，不具备数据库的操作能力

 Model ： 由Schema发布生成的模型，具有抽象属性和行为的数据库操作对

 Entity ： 由Model创建的实体，他的操作也会影响数据库
 */
module.exports.initModel = function (db, Schema) {
    // 初始化自增ID生成器
    autoinc.initialize(db);
    //定义Schema
    var UserSchema = new Schema({
        id: Number,
        username: {type: String, required: true, unique: true},
        password: {type: String, required: true},
        icon: String
    });
    //要先设置自增长id插件再发布model
    setAutoId(UserSchema, 'User');
    //将该Schema发布为Model
    //如果该Model已经发布，则可以直接通过名字索引到，如下：
    //var PersonModel = db.model('Person');
    //如果没有发布，上一段代码将会异常
    model.UserModel = db.model('User', UserSchema);
    var TagSchema = new Schema({
        id: Number,
        name: {type: String, required: true}
    });
    setAutoId(TagSchema, 'Tag');
    model.TagModel = db.model('Tag', TagSchema);

    var CatalogSchema = new Schema({
        id: Number,
        name: {type: String, required: true},
        parent: {
            type: Schema.ObjectId,
            ref: 'Catalog'
        }
    });
    setAutoId(CatalogSchema, 'Catalog');
    model.CatalogModel = db.model('Catalog', CatalogSchema);


    var ArticleSchema = new Schema({
        id: Number,
        title: {type: String, required: true},
        author: {
            type: Object,
            ref: 'User'
        },
        date: Date,
        content: String,
        tags: {type: Array, ref: 'Tag'},
        catalog: {
            type: Object,
            ref: 'Catalog'
        }
    });
    setAutoId(ArticleSchema, 'Article');
    model.ArticleModel = db.model('Article', ArticleSchema);

    var WidgetSchema = new Schema({
        id: Number,
        title: String,
        body: String,
        footer: String
    });
    setAutoId(WidgetSchema, 'widget');
    model.WidgetModel = db.model('Widget', WidgetSchema);

    require('./init');
};

module.exports.model = model;
